package cn.hicard.auth.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.hicard.auth.dao.RoleSourceDao;
import cn.hicard.auth.dao.RoleinfoDao;
import cn.hicard.auth.dao.UserRoleDao;
import cn.hicard.auth.entity.MgRoleSource;
import cn.hicard.auth.entity.MgRoleinfo;
import cn.hicard.auth.service.RoleinfoService;
import cn.hicard.util.DateHelp;

/**
 * 角色信息管理业务接口实现
 * @author zhangy
 *
 */
@Service
public class RoleinfoServiceImpl implements RoleinfoService{

	@Autowired
	private RoleinfoDao roleinfoDao;
	@Autowired
	private RoleSourceDao roleSourceDao;
	@Autowired
	private UserRoleDao userRoleDao;

	@Transactional
	public void save(MgRoleinfo role) throws Exception {
		role.setAdddatetime(DateHelp.dateTime());
		role.setModdatetime("");
		roleinfoDao.save(role);
	}

	@Transactional
	public void update(MgRoleinfo role) throws Exception {
		role.setModdatetime(DateHelp.dateTime());
		roleinfoDao.update(role);
	}

	@Transactional
	public void delete(int pkRole) throws Exception {
		// 删除与用户相关联的[用户*角色]
		userRoleDao.deleteByRole(pkRole);
		// 删除与该角色相关联的[角色*资源]
		roleSourceDao.deleteByRole(pkRole);
		// 删除角色
		roleinfoDao.delete(pkRole);
	}

	public MgRoleinfo getByPk(int pkRole) throws Exception {
		return roleinfoDao.getByPk(pkRole);
	}

	public List<MgRoleinfo> getAll() throws Exception {
		return roleinfoDao.getAll();
	}

	@Override
	public List<MgRoleinfo> getByUser(int pkUserinfo) throws Exception {
		return roleinfoDao.getByUser(pkUserinfo);
	}

	public List<Integer> findOwnSourcePks(int pkRoleinfo) throws Exception {		
		return roleSourceDao.findSourcePkByRole(pkRoleinfo);
	}

	public void saveRoleSource(int pkRole, List<MgRoleSource> rslist) throws Exception {
		// 将原有的角色的资源分本配清除
		roleSourceDao.deleteByRole(pkRole);
		// 再保存新分配的
		roleSourceDao.saveRoleSources(rslist);
	}

}
